import iconfontsData from '/@/theme/iconfont/iconfont.json';

// 定义iconfont数据结构的类型
interface IconGlyph {
	icon_id: string;
	name: string;
	font_class: string;
	unicode: string;
	unicode_decimal: number;
}

interface IconfontsData {
	id: string;
	name: string;
	font_family: string;
	css_prefix_text: string;
	description: string;
	glyphs: IconGlyph[];
}

// 字体图标 url
const cssCdnUrlList: Array<string> = [
	'//at.alicdn.com/t/c/font_4970436_eofep0qwdg.css', // iconfont图标库

];
// 第三方 js url
const jsCdnUrlList: Array<string> = [];

// 获取所有图标列表（从本地JSON）
export function getIconList(): string[] {
	const data = iconfontsData as IconfontsData;
	return data.glyphs.map((glyph: IconGlyph) => `icon-${glyph.font_class}`);
}

// 获取图标的Unicode
export function getIconUnicode(iconClass: string): string {
	const data = iconfontsData as IconfontsData;
	const cleanClass = iconClass.replace('icon-', '');
	const glyph = data.glyphs.find((item: IconGlyph) => item.font_class === cleanClass);
	return glyph ? glyph.unicode : '';
}

// 获取图标名称
export function getIconName(iconClass: string): string {
	const data = iconfontsData as IconfontsData;
	const cleanClass = iconClass.replace('icon-', '');
	const glyph = data.glyphs.find((item: IconGlyph) => item.font_class === cleanClass);
	return glyph ? glyph.name : '';
}

// 动态批量设置字体图标
export function setCssCdn() {
	if (cssCdnUrlList.length <= 0) return false;
	cssCdnUrlList.map((v) => {
		let link = document.createElement('link');
		link.rel = 'stylesheet';
		link.href = v;
		link.crossOrigin = 'anonymous';
		document.getElementsByTagName('head')[0].appendChild(link);
	});
}

// 动态批量设置第三方js
export function setJsCdn() {
	if (jsCdnUrlList.length <= 0) return false;
	jsCdnUrlList.map((v) => {
		let link = document.createElement('script');
		link.src = v;
		document.body.appendChild(link);
	});
}

/**
 * 批量设置字体图标、动态js
 * @method cssCdn 动态批量设置字体图标
 * @method jsCdn 动态批量设置第三方js
 */
const setIntroduction = {
	// 设置css
	cssCdn: () => {
		setCssCdn();
	},
	// 设置js
	jsCdn: () => {
		setJsCdn();
	},
	// 获取本地图标列表
	getIconList: () => {
		return getIconList();
	},
	// 获取图标Unicode
	getIconUnicode: (iconClass: string) => {
		return getIconUnicode(iconClass);
	},
	// 获取图标名称
	getIconName: (iconClass: string) => {
		return getIconName(iconClass);
	},
};

// 导出函数方法
export default setIntroduction;

